/**
 * axios全局配置
 */
import Qs from 'qs';
import {
  Message
} from 'element-ui';
import VueCookies from 'vue-cookies'
import {apiAddress} from '~/util/config.js'

export default function (app) {
  let axios = app.$axios;
  // 基本配置
  //axios.defaults.timeout = 10000;

  if(process.env.NODE_ENV == 'production'){//如果是生产环境
    // axios.defaults.baseURL = 'http://192.168.124.110' //线上
    axios.defaults.baseURL = apiAddress //线上
  }else{
    // axios.defaults.baseURL = '' //本地
    // axios.defaults.baseURL = 'http://192.168.124.66' //本地
    axios.defaults.baseURL = apiAddress //线上
  }

  axios.defaults.headers.common['Authorization'] = "Bearer " + app.store.state.token;
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


  //参数序列化
  axios.interceptors.request.use((config) => {
    if (config.method == 'get') {
      if (config.params) {
        let params = {}
        for (let i in config.params) {
          if (config.params[i]) {
            params[i] = config.params[i]
          }
        }
        config.params = params
      }
    }
    if (config.method === 'post') {
      config.data = Qs.stringify(config.data)
    }
    return config;
  }, (error) => {
    return Promise.reject(error)
  })
  //响应拦截器
  axios.interceptors.response.use(
    response => {
      if (response.data.code == 401) {
        /*
         * 如果请求报错是因为token不存在或过期，就重新登录
         */
        Message({
          message: app.store.state.token ? "您需要重新登录" : "您还没有登录",
          type: "warning"
        });
        app.store.commit('delToken');
        VueCookies.remove('token');
        app.redirect('/admin/login');
      }
      return response;
    },
    error => {
      return Promise.resolve(error)
    });
}
